package part4.interpreter;

import token.Token;

public class Interpreter {
    private final Lexer lexer;
    private Token currentToken;

    public Interpreter(Lexer lexer) throws Exception {
        this.lexer = lexer;
        this.currentToken = this.lexer.getNextToken();
    }

    private void error() throws Exception {
        throw new Exception("Invalid syntax");
    }

    private void eat(Token.TokenType tokenType) throws Exception {
        if (currentToken.type == tokenType){
            currentToken = lexer.getNextToken();
        }
        else {
            this.error();
        }
    }

    private int factor() throws Exception {
        Token token = currentToken;
        eat(Token.TokenType.INTEGER);
        return (Integer) token.value;
    }

    public int expr() throws Exception {
        int result = factor();

        while (currentToken.type == Token.TokenType.MUL || currentToken.type == Token.TokenType.DIV){
            Token token = currentToken;
            if (token.type == Token.TokenType.MUL){
                eat(Token.TokenType.MUL);
                result *= factor();
            }
            else {
                eat(Token.TokenType.DIV);
                result /= factor();
            }
        }

        return result;
    }
}
